﻿using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;

namespace ResilienceCompute.Tool
{
    public class SiemenPlc
    {
        private SiemensS7Net siemens;
        private bool lastReuestStart = false;
        private bool lastReuestEnd = false;
        public Action<(double, List<double>)> DataCallback;
        private string _addr;

        private readonly ContinuousPressureReader reader;

        public SiemenPlc(string ip, string addr, int channel)
        {
            _addr = addr;
            siemens = new SiemensS7Net(SiemensPLCS.S1500, ip);
            siemens.ConnectTimeOut = 2000;
            siemens.SetPersistentConnection();
            const double excitationVoltage = 5.0;      // 激励电压10V
            const double sensitivity = 1.5725;        // 1.5725 mV/V
            const double fullScaleLoad = 9807.1;       // 9.8071 kN = 9807.1 N
            reader = new ContinuousPressureReader(
            deviceName: "cDAQ1Mod1",
            channel,
            excitationVoltage: excitationVoltage,
            sensitivity: sensitivity,
            fullScaleLoad: fullScaleLoad,
            samplingRate: 1024,
            bufferSize: 1000);
            // 订阅数据处理完成事件
            reader.OnDataProcessingComplete += Reader_OnDataProcessingComplete;
            // 执行零点校准（必须在无负载状态下）
            Console.WriteLine("开始零点校准（确保无负载状态）...");
            reader.PerformZeroCalibration();
        }

        private void Reader_OnDataProcessingComplete(double[] obj)
        {
            var CollectValue = SignalFilter.HybridFilter(obj.ToList(), 50, 50);
            var result = Math.Truncate(Convert.ToSingle(MedianCalculator.CalculateMedianAverage(CollectValue))) + 32;
            siemens.Write(_addr + ".4", -result);
            siemens.Write(_addr + ".2.1", true);
            DataCallback?.Invoke((result, CollectValue));
            ExcelHelper.ExportToExcel(obj.ToList(), $"D:/Pressure/{Guid.NewGuid()}.xlsx");
        }

        public void Start()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        bool requestStart = siemens.ReadBool(_addr + ".0.0").Content;
                        if (requestStart && !lastReuestStart)//开始请求
                        {
                            lastReuestStart = true;
                            // 开始连续采集
                            Console.WriteLine("开始连续采集...");
                            reader.Start();
                            siemens.Write(_addr + ".2.0", true);
                        }
                        if (!requestStart && lastReuestStart)
                        {
                            lastReuestStart = false;
                        }
                        bool requestEnd = siemens.ReadBool(_addr + ".0.1").Content;
                        if (requestEnd && !lastReuestEnd)
                        {
                            lastReuestEnd = true;
                            reader.Stop();
                        }
                        if (!requestEnd && lastReuestEnd)
                        {
                            lastReuestEnd = false;
                        }
                    }
                    catch (Exception EX) { }
                }
            });
        }
    }
}